package com.tjmc.recruit.common.security.service;

import cn.hutool.core.util.StrUtil;
import com.tjmc.recruit.admin.api.entity.PlatformUserInfoEntity;
import com.tjmc.recruit.admin.api.feign.RemoteUserService;
import com.tjmc.recruit.common.core.constant.CommonConstants;
import com.tjmc.recruit.common.core.constant.SecurityConstants;
import com.tjmc.recruit.common.core.util.R;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.cache.CacheManager;

@Slf4j
@RequiredArgsConstructor
public class RecruitPlatformUserDetailsServiceImpl implements RecruitUserDetailsService {
	private final RemoteUserService remoteUserService;

	private final CacheManager cacheManager;

	/**
	 * 用户名密码登录
	 * @param username 用户名
	 * @return
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String username) {
		R<PlatformUserInfoEntity> result = remoteUserService.platformUser(username, SecurityConstants.FROM_IN);
		// 根据 result 构建security 框架需要的 用户对象
		PlatformUserInfoEntity custom = result.getData();
		if (custom == null) {
			throw new UsernameNotFoundException("用户不存在");
		}

		// 构造security用户
		return new RecruitUser(custom.getId(), null, custom.getUsername(), SecurityConstants.BCRYPT + custom.getPassword(), null, true, true,
				true, StrUtil.equals(custom.getStatus(), CommonConstants.STATUS_NORMAL), AuthorityUtils.NO_AUTHORITIES);
	}

	/**
	 * 是否支持此客户端校验
	 * @param clientId 目标客户端
	 * @param grantType
	 * @return true/false
	 */
	@Override
	public boolean support(String clientId, String grantType) {
		return "custom".equals(clientId);
	}

	@Override
	public int getOrder() {
		return Integer.MIN_VALUE + 1;
	}
}
